#include "ConnectionMonkey.h"

#include "WinException.h"

using namespace std;

// gracefully stop the monkey
void ConnectionMonkey::stop() {
	// tell the run() method to exit
	_doRun = false;
	// wake it up in case it is sleeping
	wakeUp();
	// wait until the thread has exited before returning
	join();
}


ConnectionMonkey::ConnectionMonkey(IConnection& con) 
	:mInterval(1000)
	,_con(con)
	,_doRun(true)
{}


void ConnectionMonkey::setInterval(int i)  {
	mInterval = i;
}


string randString() {
	static const char abc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\n";
	int len = rand() % 200;
	string result;
	for(int i=0; i<len; ++i) {
		result += abc[rand() % sizeof(abc)];
	}
	return result;
}


void ConnectionMonkey::run()
{
	_doRun = true;
	while (_doRun) {
		_con.sendString(randString());
		sleep(mInterval);
	}
}